package com.kaishengit.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.dao.UserDao;
import com.kaishengit.entity.User;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String captcha = request.getParameter("captcha");
		
		if(SimpleImageCaptchaServlet.validateResponse(request, captcha)) {
			String name = request.getParameter("username");
			String pwd = request.getParameter("password");
			if(name == null || pwd == null) {
				response.sendRedirect("index.jsp");
				return;
			}
	
			System.out.println("Name:" + name + "\tpwd:" + pwd);
			
	
			UserDao dao = new UserDao();
			User user = dao.findByNameAndPwd(name, pwd);
			if(user != null) {
				HttpSession session = request.getSession();
				
				session.setAttribute("user", user);
				response.sendRedirect("prod.jspx");
			} else {
				response.sendRedirect("index.jspx?code=10001");
			}
		} else {
			response.sendRedirect("index.jspx?code=10003");
		}
	}
}
